<?php
/*详细页面类*/
class DetailAction extends Action {
	/**展示模板*/
	public function index() {
		//dump(strlen('这是十个字符的长度是'));
		//die;
		$classID = I ( 'id' );
		$score = I ( 'score' );
		$itemid=I('itemid'); //为空
		$allitem = $this->GetItem ( $classID ); //获取第三级评论项
		$allcomment = $this->GetScore ( $classID ); //获取评价选择项
		$class_name = $this->getclassName ( $classID ); //获取中心名称
		$limitcount=session('count');  //判断已经评价的次数

		$this->assign("limitcount",$limitcount);
		$this->assign("class_id",$classID); //分类id
		$this->assign("itemid",$itemid); //
		$this->assign ( "class_name", $class_name );
		$this->assign ( 'votescore', $allcomment );  //所有评价项
		$this->assign ( 'voteitem', $allitem );
		$this->assign ( 'score', $score );
		//根据教学区或其他服务生成不同的第二级选择
		if($allitem[0]['group_ID']>0){//如果没有细分是等于0的
		 $grouplist=$this->GetGroupList($classID);
		 $this->assign("group_list",$grouplist);
		}
		
		$this->display ();
	}
	/**获取各个细节项和各项总的平均分,应用于item项*/
	public function GetItem($classID) {
		
		$sql = sprintf ( "select item_name,item_ID,group_ID,item_score,item_num  from vote_item  where class_ID=%s order by item_order", $classID );
	
		$result = M ()->query ( $sql );
		//如果字符长度不够10个字符可以补齐
		foreach ( $result as $key => $value ) {
			if ($value ['item_num'] == 0) {
				$result [$key] ['average'] = 0;
			} else {
				$result [$key] ['average'] = number_format ( $value ['item_score'] / $value ['item_num'], 2 );
			}	
		}
		return $result;
	}
	
	/**获取item的类别，查vote_group表，分居class获取分组表*/
	public function GetGroupList($classID)
	{
		$sql = sprintf ( "SELECT  group_ID,group_name,item_ids  from vote_group  where class_ID=%s and vote_group.status=1", $classID );
		$result = M ()->query ( $sql );
		return $result;
	}
	/**获取所有评分项所有item项*/
	public function GetScore($classID) {
		$sql = sprintf ( "select score_name,item_index,item_group  from vote_score  where class_ID=%s", $classID );
		$result = M ()->query ( $sql );
		return $result;
	}
	/*获取每个细节项的平均分ajax回发获取**/
	public function AjaxgetAverage() {
		$item_id = I ( 'itemid' );
		$sql = sprintf ( "SELECT  class_ID,item_score,item_num, item_score1,item_score2,item_score3,item_score4,item_score5,item_score6,item_score7,item_score8,item_score9,item_score10,item_num1,item_num2,item_num3,item_num4,item_num5,item_num6,item_num7,item_num8,item_num9,item_num10 from vote_item    where item_ID=%s   ", $item_id );
        $value = M ()->query ( $sql );
        $value=$value[0];
		//获取评价项
        $class_ID=$value['class_ID'];
        $sql = sprintf ( "select score_name,item_index  from vote_score  where class_ID=%s", $class_ID );
        $score_list = M ()->query ( $sql );
       //
        $return=array();
            foreach($score_list as $key2=>$value2){
                $index_pre=$value2['item_index']; //score表中的索引，示例为num1  num2等
                $index=substr($index_pre,-1,1);
                $score_index='item_score'.$index;

                $num_index='item_num'.$index;

                $score=$value[$score_index];
                $num=$value[$num_index];
                $average=$num==0?0:number_format ($score/ $num, 1 ); //计算平均值
                $return[]=array(
                    'num'=>$num,'score'=>$score,'average'=>$average,
                    'index'=>$index_pre
                ); //添加到数组中
            }
            $total_num=$value['item_num'];
            $arr_ajax=array(
                'total'=>$total_num==0?0:number_format($value ['item_score'] /$total_num , 2 ),
                'count'=>$total_num,
                'data'=>$return
            );
		return $this->ajaxReturn ( $arr_ajax );
	}
	/*获取服务名称**/
	public function getclassName($classid) {
		//还要根据classid获取服务名称
		$sql = sprintf ( "select class_name from vote_class where class_ID=%s", $classid );
		$results = M ()->query ( $sql );
		$class_name = $results [0] ['class_name'];
		//dump($class_name);die;
		return $class_name;
	}
	
	//单项测评
	public function voteItem() {
		//由于服务器可能不支持carbon所以用原生函数重新写一下
	date_default_timezone_set('PRC'); //设置中国时区
      //  import("ORG.MyClass.Carbon");
		//$now = Carbon::now ( 'Asia/Shanghai' );
		$ip = get_client_ip ();
	    $itemid=I('itemid');
	    $scores=I('thescore');
	    $classid=I('classid');

        //检查ip获取性
		if ($ip === null) {
		return 	$this->error ( "对不起，无法获取您的IP，无法投票" );
		}


		//查询时间是否在规定时间
		$start = session ( "start" );
		$end = session ( "end" );
		if($start==""||$end==""){//如果是直接打开第二页网址，时间是空的，应该从新从数据库查询时间
              $this->StoreLimitTosession();
            $start = session ( "start" );
            $end = session ( "end" );
		}
		
	   $now=time();//获取当前时间戳
       $theStart=  strtotime($start); //开始时间戳
       $theEnd=strtotime($end);//结束的时间戳
       $isBeteenDate= $theStart<$now&&$theEnd>$now;
       //检测是否有选中的评价项
        $scoreArr=explode('-', $scores);
        $totalscore=0;
        $totalnum=0;
        $partSql='';
        $empty=true;
        $save_arr=array(); //用于记录在score，看看测评了哪几项各给了多少分

        foreach ($scoreArr as $key=>$value)
        {
            if($value==95||$value==85||$value==65){
                $totalscore+=$value;
                $totalnum++;
                $save_arr['item_num'.($key+1)]=$value;
                $partSql.=',item_num'.($key+1).'='.'item_num'.($key+1).'+1,'.'item_score'.($key+1).'='.'item_score'.($key+1)."+$value";
                $empty=false;
            }
        }

        if($empty){
            return  $this->error("请至少选择一项进行评价，如果您都不了解可不选此栏");
        }
        if(!$isBeteenDate){
           $info="对不起，评价时间不在允许时间段内，请在下次投票时间开始时投票<br/>\n投票允许时间是".$start."到"."$end";
           $this->error($info);
        }

		//查询是否到达已规定的次数
			$count = session ( "count" );  //评价每个小项的次数
	$sql = sprintf ( "select count(*)  as num from vote_limit where record_ip='%s' and record_item=%s", $ip,$itemid );

        $result = M ()->query ( $sql );

			if ($result [0] ['num'] > $count-1) {
				$this->error("您的投票次数已经超过了规定次数，请不要再投");
			}
        //插入投票记录中
$sql= sprintf("insert into vote_limit (record_ip,record_item)VALUES('%s','%s')",$ip,$itemid);
M()->execute($sql);
        //插入记录日志中
 $sql= sprintf("insert into vote_log (time,ip,item_id,score)VALUES('%s','%s','%s','%s')",$now,$ip,$itemid,json_encode($save_arr));
  M()->execute($sql);
         //更新item表中的总分数和各项分数
      $sql=sprintf(" UPDATE vote_item SET
item_score=item_score+%s,
item_num=item_num+%s %s where item_ID=%s",$totalscore,$totalnum,$partSql,$itemid);
			   /* $sql=sprintf("
			    UPDATE vote_item SET 
item_score=item_score+300,
item_num=item_num+1,
item_num1=item_num1+1,
item_num2=item_num2+1,
item_num3=item_num3+1,
item_num4=item_num4+1,
item_num5=item_num5+1,
item_num6=item_num6+1,
item_score1=item_score1+85,
item_score2=item_score2+85,
item_score3=item_score3+85,
item_score4=item_score4+85,
item_score5=item_score5+85,
item_score6=item_score6+85 
where item_ID=1"); */
			  
      $result= M()->execute($sql);
      $allscore=$this->caculateAllScore($classid);
      if($result){  $this->success("投票成功","index.php?m=Detail&a=index&id=$classid&score=$allscore&itemid=$itemid");}
      else{$this->success("投票失败");}

	}
	/**计算总分数平均值*/
	public function  caculateAllScore($classid)
	{
			$sql = sprintf ( "select SUM(item_score) as score,SUM(item_num) as num ,vote_class.class_ID,class_name,class_image,class_keyword from vote_item,vote_class where vote_item.class_ID=vote_class.class_ID   and vote_class.class_ID=%s  " ,$classid);
			$result = M ()->query ( $sql );	
			$results = number_format ($result [0] ['score'] / $result[0]['num'], 2 ); //保留两位小数
			return $results;
	}
    //检查时间和投票次数是否允许
    public  function  check_permit(){

        $start = session ( "start" );
        $ip = get_client_ip ();
        $end = session ( "end" );
        $itemid=I('itemid');

        if($start==""||$end==""){//如果是直接打开第二页网址，时间是空的，应该从新从数据库查询时间
            $this->StoreLimitTosession();
            $start = session ( "start" );
            $end = session ( "end" );
        }

        $now=time();//获取当前时间戳
        $theStart=  strtotime($start); //开始时间戳
        $theEnd=strtotime($end);//结束的时间戳
        $isBeteenDate= $theStart<$now&&$theEnd>$now;
        if(!$isBeteenDate){
            $arr=array('flag'=>false,'msg'=>'不在允许投票的时间段内');
          return  $this->ajaxReturn ( $arr );

        }

        $count = session ( "count" );  //评价每个小项的次数
        $sql = sprintf ( "select count(*)  as num from vote_limit where record_ip='%s' and record_item=%s", $ip,$itemid );
        $result = M ()->query ( $sql );

        if ($result [0] ['num'] > $count-1) {
            $arr=array('flag'=>false,'msg'=>'您已经超过了每项栏目规定的投票次数'.$count);
            return  $this->ajaxReturn ( $arr );
        }
        $arr=array('flag'=>true,'msg'=>'允许投票');
        return  $this->ajaxReturn ( $arr );

    }
		/*将限制存储于session方便比较*/
		private  function  StoreLimitTosession()
		{
			$sql='select votetime_start as start,votetime_end as end, limit_times as times from vote_message where message_ID=1 ';
		    $result=M()->query($sql);
		    $start=$result[0]['start'];
		    $end=$result[0]['end'];
		    $count=$result[0]['times'];
		    session('start',$start);
		    session('end',$end);
		    session('count',$count);
		}

}
